<template>
  <div class="api-config-list" ref="tableContainer">
    <el-button type="primary" @click="handleCreate">新增</el-button>
    <div class="table-container">
      <el-table
          :data="apiConfigs"
          stripe
          style="width: 100%; margin-top: 20px;"
          :height="tableHeight"
          fit
      >
        <el-table-column prop="id" label="ID"  show-overflow-tooltip></el-table-column>
        <el-table-column prop="name" label="名称" width="120"></el-table-column>
        <el-table-column prop="baseUrl" label="基础 URL" show-overflow-tooltip></el-table-column>
        <el-table-column prop="path" label="路径" show-overflow-tooltip></el-table-column>
        <el-table-column prop="method" label="方法" width="100"></el-table-column>
        <el-table-column prop="requestBody" label="请求体">
          <template #default="scope">
            <el-popover
                v-if="scope.row.requestBody"
                placement="right"
                width="400"
                trigger="click"
            >
              <pre>{{ formatJson(scope.row.requestBody) }}</pre>
              <template #reference>
                <el-button type="text">查看请求体</el-button>
              </template>
            </el-popover>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="requestHeaders" label="请求头">
          <template #default="scope">
            <el-popover
                v-if="scope.row.requestHeaders"
                placement="right"
                width="400"
                trigger="click"
            >
              <pre>{{ formatJson(scope.row.requestHeaders) }}</pre>
              <template #reference>
                <el-button type="text">查看请求头</el-button>
              </template>
            </el-popover>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="requestParams" label="请求参数">
          <template #default="scope">
            <el-popover
                v-if="scope.row.requestParams"
                placement="right"
                width="400"
                trigger="click"
            >
              <pre>{{ formatJson(scope.row.requestParams) }}</pre>
              <template #reference>
                <el-button type="text">查看请求参数</el-button>
              </template>
            </el-popover>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="authConfig.name" label="关联鉴权" width="120"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="150"></el-table-column>
        <el-table-column prop="updatedAt" label="修改时间" width="150"></el-table-column>
        <el-table-column prop="enabled" label="启用">
          <template #default="scope">
            <el-switch
                v-model="scope.row.enabled"
                @change="handleEnableChange(scope.row)"
                active-color="#13ce66"
                inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="confirmDelete(scope.row.id)" style="color: #ff4d4f;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    ></el-pagination>
    <ApiConfigForm :visible="showForm" :apiConfig="currentApiConfig" @close="showForm = false" @save="handleSave"/>
  </div>
</template>

<script>
import ApiConfigForm from './ApiConfigForm.vue';
import { getApiConfigs, deleteApiConfig, saveApiConfig } from '@/services/apiService';
import { MessageBox } from 'element-ui';

export default {
  components: {
    ApiConfigForm
  },
  data() {
    return {
      apiConfigs: [],
      showForm: false,
      currentApiConfig: {},
      currentPage: 1, // 当前页码
      pageSize: 10,   // 每页显示数量
      total: 0,       // 总记录数
      tableHeight: 400 // 表格高度
    };
  },
  mounted() {
    this.fetchApiConfigs();
    this.updateTableHeight(); // 初始化表格高度
    window.addEventListener('resize', this.updateTableHeight); // 监听窗口大小变化
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.updateTableHeight);
  },
  methods: {
    // 格式化 JSON 数据
    formatJson(value) {
      try {
        if (typeof value === 'string') {
          const parsedValue = JSON.parse(value); // 先解析字符串
          return JSON.stringify(parsedValue, null, 2); // 再格式化
        } else if (typeof value === 'object') {
          return JSON.stringify(value, null, 2);
        }
        return value;
      } catch (e) {
        return value; // 如果不是 JSON 字符串，直接返回原始值
      }
    },
    // 启用/禁用切换
    handleEnableChange(data) {
      this.handleSave(data);
    },
    // 获取 API 配置列表
    async fetchApiConfigs() {
      try {
        const response = await getApiConfigs(this.currentPage, this.pageSize);
        if (response.data.success) {
          this.apiConfigs = response.data.data.records; // 从 data.data 中获取 records
          this.total = response.data.data.total;       // 从 data.data 中获取 total
        } else {
          this.$message.error(response.data.message || '获取数据失败');
        }
      } catch (error) {
        console.error('获取 API 配置列表失败:', error);
        this.$message.error('获取数据失败，请稍后重试');
      }
    },
    // 新增
    handleCreate() {
      this.currentApiConfig = {};
      this.showForm = true;
    },
    // 编辑
    handleEdit(apiConfig) {
      this.currentApiConfig = {...apiConfig};
      console.log(this.currentApiConfig)
      this.showForm = true;
    },
    // 确认删除
    confirmDelete(id) {
      MessageBox.confirm('确定要删除该 API 配置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(id);
      }).catch(() => {
        this.$message.info('已取消删除操作');
      });
    },
    // 删除
    async handleDelete(id) {
      try {
        const response = await deleteApiConfig(id);
        if (response.data.success) {
          this.$message.success('删除成功');
          this.fetchApiConfigs();
        } else {
          this.$message.error(response.data.message || '删除失败');
        }
      } catch (error) {
        console.error('删除 API 配置失败:', error);
        if (error.response && error.response.data && error.response.data.message) {
          this.$message.error(error.response.data.message);
        } else {
          this.$message.error('删除失败，请稍后重试');
        }
      }
    },
    // 保存或更新
    async handleSave(apiConfig) {
      console.log(apiConfig);
      if (typeof apiConfig.requestBody !== 'string') {
        apiConfig.requestBody = JSON.stringify(apiConfig.requestBody);
      }
      if (typeof apiConfig.requestHeaders !== 'string') {
        apiConfig.requestHeaders = JSON.stringify(apiConfig.requestHeaders);
      }

      try {
        apiConfig.authConfigId = apiConfig.authConfig?.id?? null;
        let response = await saveApiConfig(apiConfig);
        if (response.data.success) {
          this.$message.success(apiConfig.id ? '更新成功' : '新增成功');
          this.showForm = false;
          this.fetchApiConfigs();
        } else {
          this.$message.error(response.data.message || '操作失败');
        }
      } catch (error) {
        console.error('保存 API 配置失败:', error);
        if (error.response && error.response.data && error.response.data.message) {
          this.$message.error(error.response.data.message);
        } else {
          this.$message.error('保存失败，请稍后重试');
        }
      }
    },
    // 每页显示数量改变时触发
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchApiConfigs();
    },
    // 当前页码改变时触发
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchApiConfigs();
    },
    // 动态更新表格高度
    updateTableHeight() {
      const container = this.$refs.tableContainer;
      if (container) {
        const paginationHeight = 50; // 分页组件高度
        this.tableHeight = container.clientHeight - paginationHeight - 100; // 根据容器高度动态调整
      }
    }
  }
};
</script>

<style>
.api-config-list {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 40px); /* 设置容器高度为视口高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}

.table-container {
  overflow-x: auto; /* 添加水平滚动条 */
  overflow-y: auto; /* 添加垂直滚动条 */
}

pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .el-table {
    width: 100%;
    min-width: unset; /* 移除最小宽度 */
  }
}
</style>